<template>
  <div class="basicInfo flowCloumn h100">
    <div class="constentTop flowWrap">
      <span class="topBtn">
        <el-tooltip
          class="item"
          effect="dark"
          :content="addContent"
          :disabled="addDisabled"
          placement="top"
        >
          <span class="btnSpan">
            <el-popover
              class="popoverBtn"
              placement="bottom"
              width="60"
              trigger="click"
              v-if="showAddBtn"
              :disabled="!addDisabled"
            >
              <div class="addBtn" @click="toAdd('root')">在根节点新建</div>
              <div class="addBtn" @click="toAdd()">在当前节点新建</div>
              <el-button
                slot="reference"
                icon="el-icon-plus"
                class="el-button--plain"
                size="mini"
                ref="addBtn"
                :disabled="!addDisabled"
              >新建</el-button>
            </el-popover>
          </span>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="saveContent"
          :disabled="saveDisabled"
          placement="top"
        >
          <span class="btnSpan">
            <el-button
              class="el-button--plain"
              size="mini"
              icon="el-icon-check"
              @click="submit"
              v-if="showSaveBtn"
              :disabled="!saveDisabled"
            >保存</el-button>
          </span>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="deleteContent"
          :disabled="deleteDisabled"
          placement="top"
        >
          <span class="btnSpan">
            <el-button
              class="el-button--plain"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRow"
              v-if="showDeleteBtn"
              :disabled="!deleteDisabled"
            >删除</el-button>
          </span>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="moveContent"
          :disabled="moveDisabled"
          placement="top"
        >
          <span class="btnSpan">
            <el-button
              class="el-button--plain"
              size="mini"
              icon="el-icon-share"
              @click="moveMethods"
              v-if="showDeleteBtn"
              :disabled="!moveDisabled"
            >移动节点</el-button>
          </span>
        </el-tooltip>

        <el-button
          class="el-button--plain"
          size="mini"
          icon="el-icon-check"
          @click="cancel"
          v-if="showCanceln"
        >取消</el-button>
      </span>
    </div>
    <div class="constentBttom flowWrap">
      <div class="constentmain w100" v-if="showMain">
        <el-collapse v-model="activeNames" class="collapseDiv">
          <el-collapse-item name="1">
            <template slot="title">基本信息</template>
            <div class="flowWrap">
              <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData"></editForm>
            </div>
          </el-collapse-item>
          <el-collapse-item name="2" v-if="showAddBtn">
            <template slot="title">放置设备</template>
            <div class="tableDiv">
              <listTableNew v-bind="deviceSeting" ref="klTable"></listTableNew>
              <!-- <baseTable :tableSetting="deviceSeting" ref="deviceTable" key="deviceTable"></baseTable> -->
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <moveTree
      v-if="showSelete"
      :currentNode="currentNode"
      @changeSelete="submitNode"
      :showSelete.sync="showSelete"
    ></moveTree>
  </div>
</template>
<script>
import {
  updateApi, //修改
  insertApi, //新增
  deleteApi, //删除
  getDetailsApi, //详情
  moveNode,
  getEquipmentById //获取设备信息
} from "@/api/equipmentLedger/locationManage";
import moveTree from "./moveTree";
export default {
  components: { moveTree },
  props: {
    //当前设备
    currentNode: {
      type: Object,
      default: () => {
        return {};
      }
    },
    menuType: {
      type: String,
      default: "details"
    }
  },
  data() {
    return {
      queryName: "",
      pageType: "edit",
      activeNames: ["1", "2"],
      hideBtn: false,
      showSelete: false,
      showMember: false,
      selectData: [],
      treeNode: {},
      formData: {},
      addType: "",
      // showMain: false,
      showMain: true,
      basicConfig: {
        itemArr: [
          {
            label: "位置名称",
            prop: "name",
            type: "text",
            required: true,
            span: 8
          },
          {
            label: "位置编码",
            prop: "code",
            type: "text",
            required: true,
            span: 8
          },
          {
            type: "select",
            label: "位置状态",
            prop: "status",
            trigger: "change",
            required: true,
            selectOption: this.$store.getters["dirtData"]("system_app_status"),
            formatter: val => {
              return this.$store.getters["fineDirtDataName"](
                "system_app_status",
                val
              );
            },
            disabledOp: (val, option) => {
              let obj = option.find(i => i.value == val);
              return obj.disabled;
            },
            span: 8
          },
          {
            label: "关联组织",
            prop: "orgName", //多选时，字段要为数组类型
            propArr: "orgIdArr",
            idsStr: "orgId",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            option: [],
            allowCreate: false, //是否允许创建条目
            type: "dept-select", //类型
            trigger: "change",
            methods: obj => {},
            span: 8
          },
          {
            label: "经度",
            prop: "latlon1",
            type: "text",
            required: true,
            placeholder: "经度范围 (-180~180)",
            span: 8,
            rules: {
              validator: function(rule, value, callback) {
                // const longitude = /^-??(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,8})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,8}|180)$/; /* 经度 */
                const longitude = /^[\-\+]?(0(\.\d{1,10})?|([1-9](\d)?)(\.\d{1,10})?|1[0-7]\d{1}(\.\d{1,10})?|180\.0{1,10})$/; /* 经度 */
                if (value && !longitude.test(value)) {
                  return callback(new Error("请填写正确的经度！"));
                } else {
                  callback();
                }
              },
              trigger: "change"
            },
            methods: (val, data) => {
              let latlon = data.latlon2 || "";
              if (val || latlon) {
                this.changeItem(true);
              } else {
                this.changeItem(false);
              }
            }
          },
          {
            label: "纬度",
            prop: "latlon2",
            type: "text",
            placeholder: "纬度范围 (-90~90)",
            required: true,
            span: 8,
            rules: {
              validator: function(rule, value, callback) {
                // const latitude = /^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,4})?)|90(([.][0]{1,6})?))$/; /* 纬度 */
                const latitude = /^[\-\+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,10})?)$/; /* 纬度 */
                if (value && !latitude.test(value)) {
                  return callback(new Error("请填写正确的纬度！"));
                } else {
                  callback();
                }
              },
              trigger: "change"
            },
            methods: (val, data) => {
              let latlon = data.latlon1 || "";
              if (val || latlon) {
                this.changeItem(true);
              } else {
                this.changeItem(false);
              }
            }
          },
          {
            type: "select",
            label: "坐标类型",
            prop: "csysType",
            trigger: "change",
            required: false,
            selectOption: this.$store.getters["dirtData"]("csys_type"),
            formatter: val => {
              return this.$store.getters["fineDirtDataName"]("csys_type", val);
            },
            span: 8
          },
          {
            label: "有效范围",
            prop: "range",
            type: "el-number",
            placeholder: "有效范围0~1000",
            min: 0,
            max: 1000,
            required: true,
            span: 8
          },
          {
            label: "位置描述",
            prop: "desc",
            type: "textarea",
            maxlength: "100",
            span: 8,
            rows: 2
          },
          {
            label: "位置路径",
            buttonText: "",
            prop: "fullPathName",
            type: "input-button",
            disabled: true,
            span: 16,
            method: (item, row) => {
              const input = document.createElement('input')
              input.style.cssText = 'opacity: 0;';
              input.type = 'text';
              input.value = row.fullPathName; // 修改文本框的内容
              document.body.appendChild(input)
              input.select(); // 选中文本
              document.execCommand("copy"); // 执行浏览器复制命令
              this.$message({message: '位置路径复制成功',type: 'success'});
            },
          }
        ]
      },
      deviceSeting: {
        selectionShow: false,
        showCustomBtn: false,
        showFilterBtn: false,
        paginationObj: {
          pageSizes: [10, 15, 20, 25]
        },
        pageConfig: {}, //过滤器的设置参数
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 10
          },
          searchArr: []
        },
        actionList: [],
        column: [
          {
            label: "名称",
            prop: "name",
            width: "280px"
          },
          {
            label: "设备类型",
            prop: "isVirtual",
            scopeType: "formate",
            width: "110px",
            method: row => {
              return this.$store.getters["fineDirtDataName"](
                "equipment_node_type",
                row.isVirtual
              );
            }
          },
          {
            label: "设备树路径",
            prop: "fullPathName"
          }
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: val => {}
        }
      },
      deviceSelect: {
        seleteType: "device",
        radio: false,
        props: {
          label: "name",
          children: "children"
        },
        column: [
          {
            label: "设备名称",
            prop: "name"
          }
        ],
        chosedData: []
      }
    };
  },
  watch: {
    currentNode: {
      handler(val) {
        this.treeNode = Object.assign({}, val);
        if (this.pageType == "add") {
          this.cancel();
        }
        this.pageType = this.menuType;
        this.showMain = true;
        this.getDetails();
      },
      deep: true
    }
  },
  computed: {
    /* 是否显示添加按钮 */
    showAddBtn() {
      return this.pageType != "add";
    },
    /* 是否显示取消按钮 */
    showCanceln() {
      return this.pageType == "add";
    },
    /* 是否显示保存按钮 */
    showSaveBtn() {
      return this.pageType == "add" || this.treeNode.id;
    },
    /* 是否显示删除按钮 */
    showDeleteBtn() {
      //新增的时候
      return this.treeNode.id && this.pageType != "add";
    },
    addContent() {
      return this.$store.getters["isBtnAuth"]("add") ? null : "未授权此功能！";
    },
    addDisabled() {
      return this.$store.getters["isBtnAuth"]("add");
    },
    saveContent() {
      return this.$store.getters["isBtnAuth"]("edit") ? null : "未授权此功能！";
    },
    saveDisabled() {
      return this.$store.getters["isBtnAuth"]("edit");
    },
    deleteContent() {
      return this.$store.getters["isBtnAuth"]("delete")
        ? null
        : "未授权此功能！";
    },
    deleteDisabled() {
      return this.$store.getters["isBtnAuth"]("delete");
    },
    moveContent() {
      return this.$store.getters["isBtnAuth"]("move") ? null : "未授权此功能！";
    },
    moveDisabled() {
      return this.$store.getters["isBtnAuth"]("move");
    }
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let isEdit = this.$store.getters["isBtnAuth"]("edit");
      this.pageType = isEdit ? this.menuType : "details";
      if (this.pageType == "details") {
        this.basicConfig.itemArr.map(i => (i.disabled = true));
      }
    },
    //获取节点详情
    getDetails() {
      this.updateData();
      getDetailsApi(this.treeNode.id).then(res => {
        let data = res.data;
        if (data.enterLatLon) {
          let latlonArr = data.enterLatLon.split(",");
          data.latlon1 = latlonArr[0];
          data.latlon2 = latlonArr[1];
          if (data.latlon1 || data.latlon2) {
            this.changeItem(true);
          } else {
            this.changeItem(false);
          }
        } else {
          this.changeItem(false);
        }
        //关联组织
        data.orgIdArr = data.orgId;
        let option = this.$utils.getOptionData(data.orgName, data.orgId, "0");
        this.deviceSeting.data = data.equipmentList || [];
        this.$refs.basicForm.setItemOption("orgName", option);
        setTimeout(() => {
          this.formData = data;
        }, 300);
      });
    },
    updateData() {
      setTimeout(() => {
        this.$refs.klTable.searchData();
      }, 100);
    },
    //获取放置设备
    getTableData(params, sortStr) {
      let form = { ...params };
      if (sortStr) {
        form.orders = sortStr;
      }
      form.locationId = this.treeNode.id;
      getEquipmentById(form)
        .then(res => {
          let data = res.data.list || [];
          let total = res.data.total || 0;
          this.$set(this.deviceSeting, "tableData", data);
          this.$set(this.deviceSeting, "totalNumber", total);
        })
        .catch(e => {
          this.$set(this.deviceSeting, "tableData", []);
          this.$set(this.deviceSeting, "totalNumber", 0);
        });
    },
    //新建
    toAdd(type) {
      this.$refs.addBtn.$el.click();
      this.pageType = "add";
      this.changeItem(false);
      this.addType = type || "";
      this.showMain = true;
      this.formData = {};
      this.deviceSelect.chosedData = [];
      this.selectData = [];
      //清空放置设备的表格
      this.$set(this.deviceSeting, "tableData", []);
      this.$set(this.deviceSeting, "totalNumber", 0);
    },
    //保存
    async submit() {
      let basicData = await this.$refs.basicForm.getFormData();

      if (this.pageType == "add") {
        //新增的时候
        if (this.addType == "root") {
          //在根节点新增
          basicData.parentId = "0";
          basicData.parentName = "0";
          basicData.parentLevel = "0";
          basicData.level = 0;
        } else {
          //在当前节点新增
          let { id, name, level } = this.treeNode;
          basicData.parentId = id;
          basicData.parentName = name;
          basicData.parentLevel = level;
          basicData.level = this.treeNode.level + 1;
        }
      }
      let latlon1 = basicData.latlon1 || null;
      let latlon2 = basicData.latlon2 || null;
      basicData.enterLatLon = latlon1 + "," + latlon2;
      delete basicData.latlon1;
      delete basicData.latlon2;
      const actionApi = queryData => {
        return queryData.id ? updateApi(queryData) : insertApi(queryData);
      };
      actionApi(basicData).then(res => {
        this.$message.success("操作成功！");
        this.$emit("updateTree", "submit");
        this.pageType = "edit";
      });
    },
    //删除
    deleteRow() {
      let { id } = this.treeNode;
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteApi(id).then(res => {
            this.$message.success("操作成功");
            this.treeNode = {};
            this.formData = {};
            this.showMain = false;
            this.$emit("updateTree");
          });
        })
        .catch(e => {});
    },
    //取消新建
    cancel() {
      this.pageType = "edit";
      this.getDetails();
    },
    //移动节点
    moveMethods() {
      this.showSelete = true;
    },
    //移动节点
    submitNode(form) {
      moveNode(form).then(res => {
        this.$message.success("操作成功");
        this.treeNode = {};
        this.formData = {};
        this.showMain = false;
        this.$emit("updateTree");
      });
    },
    changeItem(isRequired) {
      let rule = {};
      rule.csysType = [
        {
          required: isRequired,
          message: "请选择",
          trigger: "change"
        }
      ];
      this.$refs.basicForm.setItemArrRules(rule);
    }
  }
};
</script>
<style lang="less" scoped>
.basicInfo {
  max-height: 100%;
  .constentBttom {
    max-height: calc(100% - 50px);
    overflow: auto;
  }
  .imgBlock {
    width: 300px;
    height: 150px;
  }
  .constentTop {
    justify-content: flex-end;
    margin-bottom: 15px;
  }
  .queryInput {
    /deep/.el-input__inner {
      height: 30px;
      line-height: 30px;
    }
  }
  .constentmain {
    padding-top: 10px;
    margin-left: 10px;
  }
  .popoverBtn + .el-button--primary {
    margin-left: 10px;
  }
  .el-button--primary {
    background-color: #2c77f4 !important;
    border-color: #2c77f4 !important;
  }
  .tableDiv {
    height: 500px;
  }
  .btnSpan {
    margin-left: 10px;
  }
}
.flowCloumn {
  display: flex;
  flex-flow: column nowrap;
}
.flowWrap {
  display: flex;
  flex-flow: wrap nowrap;
}
.addBtn:hover {
  color: @kr-elementUI-color;
  cursor: pointer;
}
</style>